package com.ruike.alisurface.services;

import android.app.IntentService;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.Serials.SavesimInfo;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.utils.DeviceUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.util.HashMap;

/**
 * showdoc 地址
 * <p>
 * http://showdoc.shouhuojiyun.com/web/#/38?page_id=505
 * https://www.showdoc.com.cn/293549481506172/9362876147822631
 * <p>
 * 新版的驱动和温控的查询流程
 */
public class WkandBzServiceVT extends IntentService {
    public static final String TAG = "新版的驱动和温控的查询";


    @Override
    public void onCreate() {
        super.onCreate();
        L.iTag(TAG, "onCreate");
    }

    public WkandBzServiceVT() {
        super("WkandBzService");
    }

    static HashMap<String, String> temHumMap = new HashMap<>();

    static Handler handler = new Handler(Looper.getMainLooper());
    static int checkVersion = 0;//处理多次查询板子导致的异常
    static StringBuilder qdmcpuList = new StringBuilder();
    static StringBuilder wktemhumList = new StringBuilder();
    static StringBuilder tmpEdpList = new StringBuilder();
    static String mqttTemp = "";
    static boolean isCheckTemp = false;

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        restVariable();
        SavesimInfo.setSavesimInfoCallBack(new SavesimInfo.SavesimInfoCallBack() {
            @Override
            public void onSerialPortData(String serialPortData, byte[] resultBytes) {
                if (isOutGoodsing()) {
                    return;
                }
                onEventBusResult(serialPortData, resultBytes);
            }
        });
    }

    public static void restVariable() {
        mqttTemp = "";
        qdmcpuList.delete(0, qdmcpuList.length());
        wktemhumList.delete(0, wktemhumList.length());
        tmpEdpList.delete(0, tmpEdpList.length());
        checkVersion = 0;
        temHumMap.clear();
        temHumMap.put("temid", DeviceUtils.getDeviceSn());
        elcTmpe.delete(0, elcTmpe.length());
    }

// 当一个Message Event提交的时候这个方法会被调用

    public void onEventBusResult(String serialPortData, byte[] resultBytes) {
        if (isOutGoodsing()) {
            return;
        }
        L.iTag(TAG, "要解析的信息--", serialPortData, resultBytes);
        String[] data_code = serialPortData.split(" ");
        if (resultBytes[0] >= (byte) 0x10 && resultBytes[0] < (byte) 0x16) {
            // 返回的驱动板的版本信息
            if (data_code[2].equals("1D")) {

                StringBuilder version_pc = new StringBuilder();//版本信息
                StringBuilder qdmcpu = new StringBuilder();//mcpu
                StringBuilder version_istmpc = new StringBuilder();//保存温控版是否存在的数据
                StringBuilder version_isgw = new StringBuilder();//保存是否接地线状态存在的数据
                StringBuilder version_isdsi = new StringBuilder();//保存是否掉货检测存在的数据
                for (int i = 0; i < data_code.length; i++) {
                    if (resultBytes[1] <= (byte) 0x16) {
                        if (i >= 4 && i <= 10) {
                            version_pc.append(data_code[i]);
                        }
                        if (i >= 10 && i < data_code.length - 1) {
                            qdmcpu.append(data_code[i]);
                        }
                    } else if (resultBytes[1] >= (byte) 0x18) {//新版的添加了 是否有温控版和接了地线

                        if (i >= 4 && i <= 10) {
                            version_pc.append(data_code[i]);
                        }
                        if (i >= 11 && i < 23) {
                            qdmcpu.append(data_code[i]);
                        }
                        if (i >= 23 && i < 26) {
                            tmpEdpList.append(data_code[i]);
                        }

                        if (i == 23) {
                            version_istmpc.append(data_code[i]);
                        }
                        if (i == 24) {
                            version_isgw.append(data_code[i]);
                        }
                        if (i == 25) {
                            version_isdsi.append(data_code[i]);
                        }

                    } else {
                        if (i >= 4 && i <= 9) {
                            version_pc.append(data_code[i]);
                        }
                    }
                }
                L.iTag(TAG, "温控版是否存在1-存在，2-不存在= " + version_istmpc.toString());
                if (resultBytes[1] >= (byte) 0x16) {
                    qdmcpuList.append(qdmcpu).append("|");
                    ShareUtils.getInstance().putString(SavesimInfo.MCPU, qdmcpuList.toString());
                    if (resultBytes[1] >= (byte) 0x18) {

                        int wkstatus = 2;//01-连接温控板，02-没有连接温控板
                        if (!version_istmpc.toString().isEmpty()) {
                            wkstatus = Integer.parseInt(version_istmpc.toString());
                        }
                        int dxstatu = 2;//01-连接保护地线，02-没有连接保护地线
                        if (!version_istmpc.toString().isEmpty()) {
                            dxstatu = Integer.parseInt(version_isgw.toString());
                        }
                        int dhjcstatu = 4;//掉货检测是否存在，3-存在，4-不存在
                        if (!version_isdsi.toString().isEmpty()) {
                            dhjcstatu = Integer.parseInt(version_isdsi.toString());
                        }
                        String vserion_info = String.format("驱动板版本参数： 版本号： %s  mcpu： %s" +
                                        "  \n 是否连接温控：%s  是否连接地线：%s   \n掉货检测：%s",
                                version_pc.toString() + "", qdmcpu.toString() + "",
                                wkstatus == 1 ? "连接温控板子" : "没有连接温控板子",
                                dxstatu == 1 ? "连接了地线" : "没有连接地线",
                                dhjcstatu == 3 ? "掉货检测在" : "掉货检测不在");

                        L.iTag(TAG, "新版的板子信息= " + vserion_info);
                        tmpEdpList.append("|");
                        ShareUtils.getInstance().putString(SavesimInfo.TMPEDP,
                                tmpEdpList.toString());
                    }
                }
                handler.removeCallbacksAndMessages(null);
                if (data_code[3].equals("00")) {
                    if (checkVersion < 1) {
                        ShareUtils.getInstance().putString(SavesimInfo.MV, version_pc.toString());
                        checkVersion++;
                        if (!"140C07140B0F".equals(version_pc.toString()) && !"14040F130C05".equals(version_pc.toString())) {
                            senQdModelSerials(11);
                        } else {
                            L.iTag(TAG, "tjf-当前版本不查询副柜信息--", "140C07140B0F==" + serialPortData);
                        }
                    }
                }
                if (data_code[3].equals("01")) {
                    ShareUtils.getInstance().putString(SavesimInfo.Fir, version_pc.toString());
                    senQdModelSerials(12);
                }
                if (data_code[3].equals("02")) {
                    ShareUtils.getInstance().putString(SavesimInfo.Sec, version_pc.toString());
                    senQdModelSerials(13);
                }
                if (data_code[3].equals("03")) {
                    ShareUtils.getInstance().putString(SavesimInfo.Thi, version_pc.toString());
                    senQdModelSerials(14);
                }
                if (data_code[3].equals("04")) {
                    ShareUtils.getInstance().putString(SavesimInfo.Fou, version_pc.toString());
                }
                L.iTag(TAG, "驱动板相关信息==", SavesimInfo.BzVersion(1));
                return;
            }
            //电能解析
            getCheckElectricalEnergy(serialPortData, resultBytes);
        }
        //温控 信息返回
        if (resultBytes[0] >= (byte) 0x23 && resultBytes[0] < (byte) 0x28) {
            getAnalyticalTemperatureControlDegree(serialPortData);
        }
    }

    /**
     * 解析驱动版电能数据
     *
     * @param serialPortData
     * @param resultBytes
     */
    public void getCheckElectricalEnergy(String serialPortData, byte[] resultBytes) {
        if (isOutGoodsing()) {
            return;
        }
        String[] electricalEnergyData = serialPortData.split(" ");
        if (resultBytes[1] >= (byte) 0x12 && resultBytes[2] == (byte) 0x2A) {
            handler.removeCallbacksAndMessages(null);
            String dianyashuju = electricalEnergyData[3] + electricalEnergyData[4];
            int dianya = com.voodoo.lib_utils.ByteUtils.hexToInt(dianyashuju);
            L.iTag(TAG, "dianya = " + dianyashuju + "===" + dianya);
            String dl = electricalEnergyData[5] + electricalEnergyData[6];
            double dianliu = com.voodoo.lib_utils.ByteUtils.hexToInt(dl) / 10.0;
            L.iTag(TAG, "dianliu = " + dl + "===" + dianliu);
            String gl = electricalEnergyData[7] + electricalEnergyData[8];
            int gonglu = com.voodoo.lib_utils.ByteUtils.hexToInt(gl);
            L.iTag(TAG, "gonglu = " + gl + "===" + gonglu);
            String dlz = electricalEnergyData[9] + electricalEnergyData[10] + electricalEnergyData[11];
            double dianliang = com.voodoo.lib_utils.ByteUtils.hexToInt(dlz) / 10.0;
            L.iTag(TAG, "dianliang = " + dlz + "===" + dianliang);
            String dymaxstr = electricalEnergyData[13] + electricalEnergyData[14];
            int dymax = com.voodoo.lib_utils.ByteUtils.hexToInt(dymaxstr);
            String linkWkb = electricalEnergyData[15];//连接 温控 板子

            String linkDx = electricalEnergyData[16];//连接  地线

            String electrical_energy = String.format(
                    "电能参数： 有效电压： %s     电压最大值：%s    有效电流： %s      功率：%s          电量：%s  ",
                    dianya + "", dymax + "", dianliu + "", gonglu + "", dianliang + "");
            L.iTag(TAG, electrical_energy);
            elcTmpe.append(dianyashuju).append(gl).append(dlz).append(dymaxstr).append(linkWkb).append(linkDx).append("|");
            ShareUtils.getInstance().putString(SavesimInfo.ELCTRICIRY, elcTmpe.toString());
            int address = Integer.parseInt(electricalEnergyData[0]);
            if (address + 1 > 14) {
                L.iTag(TAG, "sendSerials  所有板子电能信息都已查询完毕 准备发送电量信息 ");
                sendElctricity();
            } else if (address <= 14) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendElectricalEnergySerials(address + 1);
                    }
                }, 1000);
            }
        }
    }

    public static void sendElctricity() {
        if (isOutGoodsing()) {
            return;
        }
        HashMap<String, String> elctricityMap = new HashMap<>();
        elctricityMap.put("sn", DeviceUtils.getDeviceSn());
        if (TextUtils.isEmpty(SavesimInfo.ELCTRICIRY())) {
            L.iTag(TAG, " 准备发送查到的信息=数据为空 无法发送");
            return;
        }
        elctricityMap.put("tmpe", SavesimInfo.ELCTRICIRY());
        sendMsgCallBack(1, elctricityMap);
    }

    static StringBuilder elcTmpe = new StringBuilder();

    /**
     * 解析温控度
     *
     * @param data
     */

    public void getAnalyticalTemperatureControlDegree(String data) {
        if (isOutGoodsing()) {
            return;
        }
        String[] temp = data.split(" ");
        String head = temp[0];
        if (head.equals("23")) {
            addTemHumAndSerials(23, data);
            return;
        }
        if (head.equals("24")) {
            addTemHumAndSerials(24, data);
            return;
        }
        if (head.equals("25")) {
            addTemHumAndSerials(25, data);
            return;
        }
        if (head.equals("26")) {
            addTemHumAndSerials(26, data);
            return;
        }
        if (head.equals("27")) {
            addTemHumAndSerials(27, data);
        }
    }

    /**
     * 解析温控信息
     *
     * @param address
     * @param data
     */
    public void addTemHumAndSerials(int address, String data) {
        if (isOutGoodsing()) {
            return;
        }
        String[] temp = data.split(" ");
        String type = temp[2];
        handler.removeCallbacksAndMessages(null);
        L.iTag(TAG, "type=" + type, type.equals("01") ? "温湿度 返回 " :
                type.equals("02") ? "继电器 返回" : type.equals("03") ? "运行类型 返回" :
                        type.equals("04") ? "温控指令的返回" : "其它类型");
        if (type.equals("01")) {//温湿度
            isCheckTemp = true;
            wktemhumList.append(getMesg(data));
            sendTmpSerials(address, 4);
        } else if (type.equals("02")) {//继电器
            wktemhumList.append(getMesg(data));
            sendTmpSerials(address, 5);
        } else if (type.equals("03") && isCheckTemp) {  //运行类型
            wktemhumList.append(getMesg(data));
            L.iTag(TAG, "addTemHumAndSerials 保存温控值 并开始查询下一个板子");
            addTemHums(String.valueOf(address));
            wktemhumList.delete(0, wktemhumList.length());
            if (address + 1 > 27) {
                L.iTag(TAG, "sendSerials  所有板子都已查询完毕 ");
                sendMsgCallBack(0, temHumMap);
            } else if (address <= 26) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendTmpSerials(address + 1, 3);
                    }
                }, 1000);
            }
        } else if (type.equals("04") || !isCheckTemp) { // 设置温控指令的返回
            L.iTag(TAG, " =address=" + address, "设置温控指令返回");
        }
    }

    /**
     * 查询驱动板型号 及计时
     *
     * @param address
     */
    public static void senQdModelSerials(int address) {
        if (isOutGoodsing()) {
            return;
        }
        if (address == 10) {
            restVariable();
        }
        SystemClock.sleep(300);
        Ttys3Utils.getInstance().sendCheckVersion(address);
        L.iTag(TAG, " ==开始发送查询驱动板型号指令 ");
        handler.postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {
                if (isOutGoodsing()) {
                    return;
                }
                L.iTag(TAG, "senQdModelSerials 驱动板地址== " + address + "== 没有指令返回 ");
            }
        }, 2000);
    }

    /**
     * 查询驱动版电能信息
     *
     * @param address
     */

    public static void sendElectricalEnergySerials(int address) {
        if (isOutGoodsing()) {
            return;
        }

        L.iTag(TAG, " =查询驱动板的电能信息= ");
        if (address == 10) {
            elcTmpe.delete(0, elcTmpe.length());
        }
        SystemClock.sleep(300);
        int ark = 10;
        switch (address) {
            case 10:
            case 23:
                ark = 10;
                break;
            case 11:
            case 24:
                ark = 11;
                break;
            case 12:
            case 25:
                ark = 12;
                break;
            case 13:
            case 26:
                ark = 13;
                break;
            case 14:
            case 27:
                ark = 14;
                break;
        }
        Ttys3Utils.getInstance().sendCheckElectricalEnergy(ark);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.iTag(TAG, "查询驱动板的电能信息== 没有指令返回   准备发送电量信息");
                sendElctricity();
            }
        }, 2000);

    }

    /**
     * 查询温控板 信息
     *
     * @param address
     */
    public static void sendTmpSerials(int address, int type) {
        if (isOutGoodsing()) {
            return;
        }
        if (address == 23 && type == 3) {
            restVariable();
        }
        SystemClock.sleep(300);
        Ttys3Utils.getInstance().sendCheckWKVersion(address, type);
        L.iTag(TAG, " ==开始发送查询温控相关指令 ");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.iTag(TAG, "查询温控相关== " + address + " 类型==" + type + "== 没有指令返回 ");
                sendMsgCallBack(0, temHumMap);
            }
        }, 2000);
    }

    public static void sendMsgCallBack(int sendType, HashMap<String, String> jsonStr) {
        if (isOutGoodsing()) {
            return;
        }
        if (jsonStr.isEmpty()) {
            L.iTag(TAG, " 准备发送查到的信息=数据为空 无法发送");
            return;
        }

        if (sendType == 0) {
            String temhum = jsonStr.get(SavesimInfo.temhum);
            if (TextUtils.isEmpty(temhum)) {
                L.iTag(TAG, " 准备发送查到的信息=数据为空 无法发送");
                return;
            }
        }

        String json = GsonUtils.MapToJson(jsonStr);
        L.iTag(TAG, " 准备发送查到的信息=" + json);
        isCheckTemp = false;
        if (SavesimInfo.mSendInfoCallBack != null) {
            SavesimInfo.mSendInfoCallBack.onMsg(sendType, json);
        }
    }

    /**
     * 设置温控指令
     *
     * @param address
     */
    public static void sendTempSingleSerials(int address, String data) {
        if (isOutGoodsing()) {
            return;
        }
        mqttTemp = data;
        if (TextUtils.isEmpty(mqttTemp)) {
            L.iTag(TAG, " == 数据为空无法发送 ");
            return;
        }
        SystemClock.sleep(300);
        Ttys3Utils.getInstance().sendTempSerials(address, data);
        L.iTag(TAG, " ==开始发送设置温控指令 ");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.iTag(TAG,
                        "sendSerials 地址== " + address + "  =设置温控指令= 没有指令返回 ");
                mqttTemp = "";
            }
        }, 2000);
    }

    public void addTemHums(String address) {
        if (isOutGoodsing()) {
            return;
        }
        if (address.equals("23")) {
            temHumMap.put(SavesimInfo.temhum, wktemhumList.toString());
        }
        if (address.equals("24")) {
            temHumMap.put(SavesimInfo.temhum1, wktemhumList.toString());
        }
        if (address.equals("25")) {
            temHumMap.put(SavesimInfo.temhum2, wktemhumList.toString());
        }
        if (address.equals("26")) {
            temHumMap.put(SavesimInfo.temhum3, wktemhumList.toString());
        }
        if (address.equals("27")) {
            temHumMap.put(SavesimInfo.temhum4, wktemhumList.toString());
        }
        L.iTag(TAG, "温控值相关信息==", GsonUtils.MapToJson(temHumMap));
    }

    // =================== 以下这两个方法实现的功能是去掉后两位即校验位，再去掉前4位即地址和数据长度位，剩下纯数据
    private String getMesg(String msg) {
        if (isOutGoodsing()) {
            return null;
        }
        String date = msg.replaceAll(" ", "");
        if (date.equals("")) {
            return null;
        }
        String strm = date.substring(0, date.length() - 2);
        return truncateHeadString(strm, 4);
    }

    public String truncateHeadString(String origin, int count) {
        if (origin == null || origin.length() < count) {
            return null;
        }
        char[] arr = origin.toCharArray();
        char[] ret = new char[arr.length - count];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = arr[i + count];
        }
        return String.copyValueOf(ret);
    }

    public static boolean isOutGoodsing() {
        if (Constant.showShop) {
            L.e(TAG, "正在出货中");
            return true;
        }
        return false;
    }
}
